package com.dearbinge.web.user.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.dearbinge.data.api.user.UserAuthenticationManageService;
import com.dearbinge.data.api.user.UserService;
import com.dearbinge.data.pojo.user.User;
import com.dearbinge.data.pojo.user.UserAuthenticationManage;
import com.dearbinge.utils.KdniaoTrackQueryAPI;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.httpClient.ApiRequest;
import com.dearbinge.utils.httpClient.ApiResponse;

/**
 * 认证
 * @author aiche
 *
 */
@SuppressWarnings("all")
@RestController
@CrossOrigin
@RequestMapping("/authentication")
@EnableAutoConfiguration
public class authenticationController extends WebMvcConfigurerAdapter {

	@Autowired
	private UserAuthenticationManageService userAuthenticationManageService;

	@Autowired
	private UserService UserService;


	@ApiOperation(value = "活体认证（新增身份证活体照片等信息）", notes = "活体认证（新增身份证活体照片等信息）")
	@RequestMapping(value = "/addCrad", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "cardJust",value = "身份证正面",paramType="query"),
		 @ApiImplicitParam(name = "cardBack",value = "身份证反面",paramType="query"),
		 @ApiImplicitParam(name = "name",value = "真实姓名",paramType="query"),
		 @ApiImplicitParam(name = "idcard",value = "身份证号码",paramType="query"),
		 @ApiImplicitParam(name = "photo",value = "活体照片",paramType="query"),
		 @ApiImplicitParam(name = "userId",value = "用户id",paramType="query",required=true),
		 @ApiImplicitParam(name = "photoStat",value = "用户活体认证状态",paramType="query"),
	})
	public ResultMsg<String> addCrad(@RequestBody JSONObject jsonObject) {
		String cardJust=jsonObject.get("cardJust").toString();
		String cardBack=jsonObject.get("cardBack").toString();
		String photo=jsonObject.get("photo").toString();
		String photoStat=jsonObject.get("photoStat").toString();

		String name=jsonObject.get("name").toString();
		String idcard=jsonObject.get("idcard").toString();
		Integer userId=Integer.valueOf(jsonObject.get("userId").toString());
		UserAuthenticationManage userAuthenticationManage = userAuthenticationManageService.getUserAuthenticationManageByUserId(userId);
		if(!StringUtils.isEmpty(userAuthenticationManage)){
			if(!userAuthenticationManage.getUserName().equals(name)||!userAuthenticationManage.getCardNo().toUpperCase().equals(idcard.toUpperCase())){
				return ResultMsg.error(501, "身份证姓名和实名认证时不一致，请重新认证！");
			}
		}else{
			userAuthenticationManage = new UserAuthenticationManage();
		}

		if(!StringUtils.isEmpty( jsonObject.get("userId"))){
			userId=Integer.valueOf((String) jsonObject.get("userId"));
		}
		try {
			//数据保存到认证表
			userAuthenticationManage.setCardJust(cardJust);
			userAuthenticationManage.setCardBack(cardBack);
			userAuthenticationManage.setPhoto(photo);
			userAuthenticationManage.setPhotoStat(photoStat);
			userAuthenticationManage.setUserId(userId);
			userAuthenticationManageService.insert(userAuthenticationManage);
			return ResultMsg.ok("200");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}


	@ApiOperation(value = "实名认证", notes = "实名认证")
	@RequestMapping(value = "/personal", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "type",value = "1用户  2店铺",paramType="query",required=true),
		 @ApiImplicitParam(name = "name",value = "用户名字",paramType="query",required=true),
		 @ApiImplicitParam(name = "idcard",value = "身份证号码",paramType="query",required=true),
		 @ApiImplicitParam(name = "userId",value = "用户id",paramType="query"),
		 @ApiImplicitParam(name = "shopId",value = "店铺id",paramType="query")
	})
	public ResultMsg<JSONObject> personal(@RequestBody JSONObject jsonObject) {
		String name=jsonObject.get("name").toString();
		String idcard=jsonObject.get("idcard").toString();
		String type=(String) jsonObject.get("type");
		Integer userId = null ;
		Integer shopId = null;
		if(!StringUtils.isEmpty( jsonObject.get("userId"))){
			userId=Integer.valueOf((String) jsonObject.get("userId"));
		}
		if(!StringUtils.isEmpty( jsonObject.get("shopId"))){
			shopId=Integer.valueOf((String) jsonObject.get("shopId"));
		}
		try {
			ApiResponse api = new ApiRequest("http://api.chinadatapay.com/communication/personal/1882",ApiRequest.Verb.POST)
			.charset("UTF-8")
			.params("key", "19f9fc9037e1d48615d314f9bb6020e6")
			.params("name", name)
			.params("idcard", idcard)
			.send();
			String result = new String(api.getContent(), "UTF-8");
			JSONObject json = JSONObject.fromObject(result);
			//数据保存到认证表
			UserAuthenticationManage userAuthenticationManage = new UserAuthenticationManage();
			userAuthenticationManage.setUserName(name);
			userAuthenticationManage.setCardNo(idcard);
			userAuthenticationManage.setUserId(userId);
			userAuthenticationManage.setShpoManageId(shopId);
			if("10000".equals(json.get("code"))){
				json = JSONObject.fromObject(json.get("data"));
				if(json.get("result").equals("1")){
					userAuthenticationManage.setCardStat("1");
					userAuthenticationManageService.insert(userAuthenticationManage);
					if(type.equals("1")){
						User user = new User();
						user.setId(userId);
						user.setCertified(true);
						UserService.update(user);//修改用户认证状态
					}
					return ResultMsg.ok(json);
				}else{
					return ResultMsg.error(501, "实名认证失败，请重新认证！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}

	@ApiOperation(value = "企业三要素核验", notes = "企业三要素核验")
	@RequestMapping(value = "companySafety", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "company",value = "企业名字",paramType="query",required=true),
		 @ApiImplicitParam(name = "creditcode",value = "统一社会信用代码",paramType="query",required=true),
		 @ApiImplicitParam(name = "name",value = "法定代表人姓名",paramType="query",required=true),
		 @ApiImplicitParam(name = "userId",value = "用户id",paramType="query"),
		 @ApiImplicitParam(name = "shopId",value = "店铺id",paramType="query")
	})
	public ResultMsg<String> companySafety(@RequestBody JSONObject jsonObject) {
		String company=(String) jsonObject.get("company");
		String creditcode=(String) jsonObject.get("creditcode");
		String name=(String) jsonObject.get("name");
		Integer userId = null ;
		Integer shopId = null;
		if(!StringUtils.isEmpty( jsonObject.get("userId"))){
			userId=Integer.valueOf((String) jsonObject.get("userId"));
		}
		if(!StringUtils.isEmpty( jsonObject.get("shopId"))){
			shopId=Integer.valueOf((String) jsonObject.get("shopId"));
		}
		try {
			ApiResponse api = new ApiRequest("http://api.chinadatapay.com/government/safety/2223",ApiRequest.Verb.POST)
			.charset("UTF-8")
			.params("key", "d1695c2999bd8226f6ffab5a2fcb7456")
			.params("company", company)//company
			.params("creditcode", creditcode)//统一社会信用代码
			.params("name", name)//法定代表人姓名
			.send();
			String result = new String(api.getContent(), "UTF-8");
			JSONObject json = JSONObject.fromObject(result);
			//数据保存到认证表
			UserAuthenticationManage userAuthenticationManage = new UserAuthenticationManage();
			userAuthenticationManage.setCompany(company);
			userAuthenticationManage.setCreditcode(creditcode);
			userAuthenticationManage.setUserName(name);
			userAuthenticationManage.setUserId(userId);
			userAuthenticationManage.setShpoManageId(shopId);
			if("10000".equals(json.get("code"))){
				json = JSONObject.fromObject(json.get("data"));
				if(json.get("state").equals("1")){
					userAuthenticationManage.setCompanyStat("1");
					userAuthenticationManageService.insert(userAuthenticationManage);
					return ResultMsg.ok("1");
				}else{
					return ResultMsg.error(501, "企业三要素核验失败，请修改数据后重新认证！");
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}


	/**
	 *
	 * @param type 1用户  2店铺
	 * @param name
	 * @param idcard
	 * @param mobile
	 * @param userId
	 * @param shopId
	 * @return
	 */
	@ApiOperation(value = "全网手机三要素验证", notes = "全网手机三要素验证")
	@RequestMapping(value = "/mobilePersonal", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "type",value = "1用户  2店铺",paramType="query",required=true),
		 @ApiImplicitParam(name = "name",value = "姓名",paramType="query",required=true),
		 @ApiImplicitParam(name = "idcard",value = "身份证号",paramType="query",required=true),
		 @ApiImplicitParam(name = "mobile",value = "手机号",paramType="query",required=true),
		 @ApiImplicitParam(name = "userId",value = "用户id",paramType="query"),
		 @ApiImplicitParam(name = "shopId",value = "店铺id",paramType="query")
	})
	public ResultMsg<JSONObject> mobilePersonal(@RequestBody JSONObject jsonObject) {
		String idcard=(String) jsonObject.get("idcard");
		String name=(String) jsonObject.get("name");
		String mobile=(String) jsonObject.get("mobile");
		String type=(String) jsonObject.get("type");
		Integer userId = null ;
		Integer shopId = null;
		if(!StringUtils.isEmpty( jsonObject.get("userId"))){
			userId=Integer.valueOf((String) jsonObject.get("userId"));
		}
		if(!StringUtils.isEmpty( jsonObject.get("shopId"))){
			shopId=Integer.valueOf((String) jsonObject.get("shopId"));
		}
		try {
			ApiResponse api = new ApiRequest("http://api.chinadatapay.com/communication/personal/1979",ApiRequest.Verb.POST)
			.charset("UTF-8")
			.params("key", "b3e9c23a1d56aa7b0d06674a041281ca")
			.params("name", name)
			.params("idcard", idcard)
			.params("mobile", mobile)
			.send();
			String result = new String(api.getContent(), "UTF-8");
			JSONObject json = JSONObject.fromObject(result);
			//数据保存到认证表
			UserAuthenticationManage userAuthenticationManage = new UserAuthenticationManage();
			userAuthenticationManage.setCardNo(idcard);
			userAuthenticationManage.setUserName(name);
			if(type.equals("1")){
				userAuthenticationManage.setUserMobile(mobile);
			}else if(type.equals("2")){
				userAuthenticationManage.setShopMobile(mobile);
			}
			userAuthenticationManage.setUserId(userId);
			userAuthenticationManage.setShpoManageId(shopId);
			if("10000".equals(json.get("code"))){
				json = JSONObject.fromObject(json.get("data"));
				if(json.get("state").equals("1")){
					userAuthenticationManage.setUserMobileStat("1");
					userAuthenticationManageService.insert(userAuthenticationManage);
					return ResultMsg.ok(json);
				}else{
					return ResultMsg.error(501, "全网手机三要素验证认证失败，请修改后重新认证！");
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}

	@ApiOperation(value = "银行卡四要素验证", notes = "银行卡四要素验证")
	@RequestMapping(value = "/idcardPersonal", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "name",value = "姓名",paramType="query"),
		 @ApiImplicitParam(name = "accNo",value = "银行卡号",paramType="query"),
		 @ApiImplicitParam(name = "mobile",value = "手机号",paramType="query"),
		 @ApiImplicitParam(name = "idcard",value = "身份证号",paramType="query"),
		 @ApiImplicitParam(name = "userId",value = "用户id",paramType="query"),
		 @ApiImplicitParam(name = "shopId",value = "店铺id",paramType="query")
	})
	public ResultMsg<JSONObject> idcardPersonal(@RequestBody JSONObject jsonObject) {
		String name=(String) jsonObject.get("name");
		String mobile=(String) jsonObject.get("mobile");
		String accNo=(String) jsonObject.get("accNo");
		String idcard=(String) jsonObject.get("idcard");
		Integer userId = null ;
		Integer shopId = null;
		if(!StringUtils.isEmpty( jsonObject.get("userId"))){
			userId=Integer.valueOf((String) jsonObject.get("userId"));
		}
		if(!StringUtils.isEmpty( jsonObject.get("shopId"))){
			shopId=Integer.valueOf((String) jsonObject.get("shopId"));
		}
		try {
			ApiResponse api = new ApiRequest("http://api.chinadatapay.com/communication/personal/1887",ApiRequest.Verb.POST)
			.charset("UTF-8")
			.params("key", "3977010160f6cbcd4cdce4fa455b46b4")
			.params("name", name)
			.params("mobile", mobile)
			.params("acc_no", accNo)//银行卡号
			.params("idcard", idcard)
			.send();
			String result = new String(api.getContent(), "UTF-8");
			JSONObject json = JSONObject.fromObject(result);
			//数据保存到认证表
			UserAuthenticationManage userAuthenticationManage = new UserAuthenticationManage();
			userAuthenticationManage.setCardNo(idcard);
			userAuthenticationManage.setBankCard(accNo);
			userAuthenticationManage.setShopMobile(mobile);
			userAuthenticationManage.setUserName(name);
			userAuthenticationManage.setUserId(userId);
			userAuthenticationManage.setShpoManageId(shopId);
			if("10000".equals(json.get("code"))){
				json = JSONObject.fromObject(json.get("data"));
				if(json.get("state").equals("1")){
					userAuthenticationManage.setBankStat("1");
					userAuthenticationManageService.insert(userAuthenticationManage);
					return ResultMsg.ok(json);
				}else{
					return ResultMsg.error(501, "银行卡四要素验证失败，请修改数据后重新提交！");
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}


	/**
	 *
	 * @param ShipperCode  快递公司编码
	 * @param LogisticCode  快递单号
	 * @return
	 */
	@CrossOrigin
	@ApiOperation(value = "物流轨迹查询", notes = "物流轨迹查询")
	@RequestMapping(value = "/exterfaceInvoke", method = RequestMethod.POST)
	@ApiImplicitParams({
		 @ApiImplicitParam(name = "ShipperCode",value = "快递公司编码",paramType="query",required=true),
		 @ApiImplicitParam(name = "LogisticCode",value = "快递单号",paramType="query",required=true)
	})
	public ResultMsg<String> exterfaceInvoke(@RequestBody JSONObject jsonObject) {
		String ShipperCode=(String) jsonObject.get("ShipperCode");
		String LogisticCode=(String) jsonObject.get("LogisticCode");
		try {
			KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
			String orderTracesByJson = api.getOrderTracesByJson(ShipperCode,LogisticCode);
			JSONObject json = JSONObject.fromObject(orderTracesByJson);
			return ResultMsg.ok(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultMsg.error(500, "error");
	}


//	public static void main1(String[] args) {
//		KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
//		try {
//			String orderTracesByJson = api.getOrderTracesByJson("YD","3968571462494");
//			System.out.println("orderTracesByJson=="+orderTracesByJson);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}


	@RequestMapping(value = "/aaaaa", method = RequestMethod.POST)
	public ResultMsg<String> auditStatus(@RequestBody JSONObject jsonObject) {
		System.out.println("aaaa="+jsonObject);
		String status = "true";
		try {
			ResultMsg.okMsg(status);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.okMsg(status);
		}
		return ResultMsg.okMsg(status);
	}

}
